package com.axis2.common.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author yemulin
 * @create 2012-8-20 上午10:48:43
 */
public class XmlUtil {

	private Document doc = null;

	public XmlUtil(String xml) throws DocumentException {
		StringReader reader = new StringReader(xml.trim());
		SAXReader saxReader = new SAXReader();
		doc = saxReader.read(reader);

	}

	// 根据xpath路径获取xml节点值
	public String getNodeValue(String xpath) {
		String result=null;
		Node node = doc.selectSingleNode(xpath);
		if(node!=null){		
			result=node.getText();
		}
		return result;

	}

	/**
	 *  根据xpath路径获取xml节点的xml片段
	 * @param xpath
	 * @return
	 */
	public String getNodeXml(String xpath) {
		String result=null;
		Node node = doc.selectSingleNode(xpath);
		if(node!=null){
			result=node.asXML();
		}
		return result;

	}

	/**
	 * 解析返回的xml到map
	 * @author xxliu
	 * @param mingwen
	 * @return
	 */
	public static Map xmlToMap(String mingwen){
	    mingwen = mingwen.replaceAll("(?<=>)\\s+(?=<)", "");
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		docBuilderFactory.setNamespaceAware(true);
		DocumentBuilder docBuilder;
		org.w3c.dom.Document doc;
		HashMap dataMap = new HashMap();
	    try {
			docBuilder = docBuilderFactory.newDocumentBuilder(); 
			doc = docBuilder.parse(new ByteArrayInputStream(mingwen.getBytes()));		
			org.w3c.dom.Node messageNode = doc.getElementsByTagName("Message").item(0);
			NodeList nodeList = messageNode.getFirstChild().getChildNodes();			
			for(int i=0; i<nodeList.getLength(); i++){
				org.w3c.dom.Node node = nodeList.item(i);
				if(node.getFirstChild() == null){
					dataMap.put(node.getNodeName(),"");	
				}else{
					if(node.getFirstChild().hasChildNodes()){
						NodeList subNodeList = node.getChildNodes();
						String[] lists = new String[subNodeList.getLength()];
						for (int j=0; j<subNodeList.getLength(); j++){
							org.w3c.dom.Node subNode = subNodeList.item(j);
							lists[j] = subNode.getFirstChild().getNodeValue();
						}
						dataMap.put(node.getNodeName(),lists);	
					}else{
						dataMap.put(node.getNodeName(),node.getFirstChild().getNodeValue());	
					}
				}
			}
	    } catch (Exception e) {
			e.printStackTrace();
		} 
		return dataMap;
	}
	/**
	 * 解析返回的xml到map
	 * @author xxliu
	 * @param mingwen
	 * @return
	 */
	public static Map xmlToMap(String mingwen,String root){
	    mingwen = mingwen.replaceAll("(?<=>)\\s+(?=<)", "");
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		docBuilderFactory.setNamespaceAware(true);
		DocumentBuilder docBuilder;
		org.w3c.dom.Document doc;
		HashMap dataMap = new HashMap();
	    try {
			docBuilder = docBuilderFactory.newDocumentBuilder(); 
			doc = docBuilder.parse(new ByteArrayInputStream(mingwen.getBytes()));		
			org.w3c.dom.Node messageNode = doc.getElementsByTagName(root).item(0);
			NodeList nodeList = messageNode.getFirstChild().getChildNodes();			
			for(int i=0; i<nodeList.getLength(); i++){
				org.w3c.dom.Node node = nodeList.item(i);
				if(node.getFirstChild() == null){
					dataMap.put(node.getNodeName(),"");	
				}else{
					if(node.getFirstChild().hasChildNodes()){
						NodeList subNodeList = node.getChildNodes();
						String[] lists = new String[subNodeList.getLength()];
						for (int j=0; j<subNodeList.getLength(); j++){
							org.w3c.dom.Node subNode = subNodeList.item(j);
							lists[j] = subNode.getFirstChild().getNodeValue();
						}
						dataMap.put(node.getNodeName(),lists);	
					}else{
						dataMap.put(node.getNodeName(),node.getFirstChild().getNodeValue());	
					}
				}
			}
	    } catch (Exception e) {
			e.printStackTrace();
		} 
		return dataMap;
	}
	
	
	public static void main(String avs[]) throws DocumentException {
		XmlUtil a = new XmlUtil("<message><head><ip>152</ip></head><body><bankurl>45685</bankurl> <bankip>192.168.12.2</bankip></body></message>");
		System.out.println(a.getNodeXml("/message/body"));
//		String resMsg = "<message><INFO><RespDate>20160816</RespDate><RespTransID>2016081600000002106</RespTransID><RespCode>00</RespCode><RespDesc>交易成功</RespDesc><RealTransAmount>0.01</RealTransAmount></INFO></message>";
		String resMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><INFO><RespDate>20160816</RespDate><RespTransID>2016081600000002106</RespTransID><RespCode>00</RespCode><RespDesc>交易成功</RespDesc><RealTransAmount>0.01</RealTransAmount></INFO>";
		String[] res = resMsg.split("<INFO>");
		String s = "<message>"+res[1]+"</message>";
		 System.out.println(s);
		Map<String,String> map = XmlUtil.xmlToMap("<message><INFO>"+res[1]+"</message>","message");
		System.out.println(map.size()+"=========");
		 for (String key : map.keySet()) {
			 System.out.println("key= "+ key + " and value= " + map.get(key));
		  }
		 
		 XmlUtil  re1 = new XmlUtil( "<?xml version=\"1.0\" encoding=\"GBK\"?><STP><HEAD><TRNCODE>PAY</TRNCODE><VERSION>3.0</VERSION><RETCODE>AAAAAAA</RETCODE><ERRMSG></ERRMSG><DSFSN>201608160000001</DSFSN><TRNSN>20160816000000447027</TRNSN><TRNDATE>20241101</TRNDATE></HEAD></STP>");
			
		 XmlUtil  re2 = new XmlUtil( "<?xml version=\"1.0\" encoding=\"GBK\"?><STP><HEAD><TRNCODE>QRYRST</TRNCODE><VERSION>3.0</VERSION><RETCODE>AAAAAAA</RETCODE><ERRMSG></ERRMSG><DSFSN>2016020611010001</DSFSN><TRNSN></TRNSN><TRNDATE></TRNDATE></HEAD><BODY><QDSFSN>201608160000001</QDSFSN><ACCCODE>65010153000000047</ACCCODE><ACCNAME>浦发2003010688</ACCNAME><BIZTYPE> </BIZTYPE><MERNO>1158934013</MERNO><MERNAME>ceshi</MERNAME><AMOUNT>1</AMOUNT><DSFTIME>133332</DSFTIME><ORETCODE>AAAAAAA</ORETCODE><OERRMSG></OERRMSG><REMARK> </REMARK></BODY></STP>");
		 
		 String head = re1.getNodeXml("/STP/HEAD");	
		 String body = re1.getNodeXml("/STP/BODY");		
		 System.out.println(re2.getNodeXml("/STP/HEAD"));	
		 System.out.println(re2.getNodeXml("/STP/BODY"));	
	}
}
